package com.ruiysoft.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.ruiysoft.controller.wx.res.JsSignResponse;
import com.ruiysoft.entity.order.OrderMain;
import com.ruiysoft.entity.order.OrderPayTransaction;
import com.ruiysoft.entity.sys.SysShopPayPlatform;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.order.IOrderCusPayService;
import com.ruiysoft.service.order.IOrderPayTransactionService;
import com.ruiysoft.service.order.anno.OrderOperate;
import com.ruiysoft.service.order.consts.OrderDBStatusEnum;
import com.ruiysoft.service.order.consts.OrderOperateTypeEnum;
import com.ruiysoft.service.order.facade.OrderCusPayFacade;
import com.ruiysoft.service.order.facade.OrderPubFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Date : 2018/12/1
 *
 * @author WenJialu
 */
@Service
public class OrderCusPayServiceImpl implements IOrderCusPayService {

	@Resource
	IOrderPayTransactionService orderPayTransactionService;

	@Resource
	OrderPubFacade orderPubFacade;
	@Resource
	OrderCusPayFacade orderCusPayFacade;

	/**
	 * 交易流水
	 *
	 *
	 * @param payPlatform
	 * @param orderNo
	 * @return
	 */
	@Override
	@OrderOperate(orderNo = "#orderNo", operateType = OrderOperateTypeEnum.GET_GENERATE_PAY_TRANSACTION, operatorId = "#userId")
	public Result<JsSignResponse> getOrGeneratePayTransaction(SysShopPayPlatform payPlatform, Long userId, Long shopId, String openId, String orderNo) {
		OrderMain orderMain = StringUtils.isBlank(orderNo) ? null : orderPubFacade.getOrderMain(orderNo);
		if (null == orderMain || !OrderDBStatusEnum.CUSTOMER_CONFIRMED_WAITING_FOR_PAYMENT.getCode().equals(orderMain.getStatus())) {
			return null;
		} else {
			OrderPayTransaction pt = orderCusPayFacade.getOrderPayTransaction(orderNo);
			if (null != pt) {
				return ResultGenerator.genSuccessResult(JSON.parseObject(pt.getJsSign(), JsSignResponse.class));
			} else {
				return orderCusPayFacade.generateOrderPayTransaction(orderMain);
			}
		}

	}
}
